<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Admin\User;
use App\Models\Admin\Order;
use App\Models\Admin\Grade;
use DB, Auth;
use App\Models\Admin\DealRecord;
use App\Models\Admin\TeamAward;
use App\Models\Admin\TotalBonusPool;
use App\Models\Admin\DailyAmount;
use App\Exports\OnePoolExport;
use Excel;
use App\Exports\DailyAmountExport;


class MemberController extends Controller
{
    // 军功章显示
    public function jgz_list(Request $request)
    {
        // 读取店铺ID
        $user = Auth::guard('admin')->user();
        if ($user->store_id === 0) {
            // 超管必需选择店铺
            $store_id = $request['storeId'];
            if (empty($store_id)) {
                return self::errorClient(['info' => '请输入店铺ID'.$store_id]);
            }
        } else {
            // 否则 获取用户本身代表的店铺
            $store_id = $user->store_id;
        }
        $User = new User;
        $Order = new Order;
        $deal = new DealRecord;
        $beg = date('Y-m-1 00:00:00',strtotime('last month'));
        $end = date('Y-m-d 23:59:59',strtotime(date('Y-m-1').'-1 day'));
        
        $min_level_arr = TeamAward::where('store_id', $store_id)->first();

        $user_send = $deal->join('users as u','u.id',"=",'deal_records.user_id')
         ->where('deal_records.store_id',$store_id)->where('deal_records.jm_type',3)->where('deal_records.status',3)->where('deal_records.is_set',0)->whereBetween('deal_records.created_at',[$beg, $end])
         ->groupBy('deal_records.user_id')
         ->select('u.id',DB::raw('SUM(deal_records.amount) as amountSum'),'u.gold','u.grade','u.jgz','u.grade_at','u.is_partner','u.partner_at')
         ->get()->toArray();
        
        $userIds = [];
        foreach ($user_send as $key => $value) {
            //VIP
                if($value['grade'] >= $min_level_arr['min_level'] && $value['grade_at'] <= $end){
                    //需要发放奖金的用户
                    array_push($userIds,$value['id']);
                }
                //报单中心
                if($value['is_partner'] == 1 && $value['partner_at'] <= $end){
                    //需要发放奖金的用户
                    array_push($userIds,$value['id']);
                }
        }
        $userIds = array_unique($userIds);
        $amountSum = $deal->whereIn('user_id',$userIds)->where('store_id',$store_id)->where('jm_type',3)->where('status',3)->where('is_set',0)->whereBetween('created_at',[$beg, $end])->sum('amount');
        $amountSum = $amountSum/100;
        if ($amountSum == 0) {
            return self::errorClient(['info' => $min_level_arr['award_name'].'为0，无可发放内容']);
        }
        
        $grade = new Grade;
        $gradeInfo = $grade->gradeOptions($store_id);
        //上个月总奖金  1号奖金池总计
        $poolModel = $deal->where('store_id',$store_id)->whereIn('deal_type',[21,30])->where('status',3)->where('is_set',0)->whereBetween('created_at',[$beg, $end]);
        $poolSum = $poolModel->sum('amount');
        $poolSum = $poolSum/100;

        //保留两位小数  不四舍五入  小数位取小数点后两位
        $num = ($poolSum/$amountSum)*1000;
        if($num >= 1){
            $person_get = floor($num)/1000;
        }else{
            $person_get = 0;
        }
    
        $send_reward = 0;// 发放出的奖金, 与应发放奖金有一定的差值, 得到差值 并 进行处理
        $arr = [];
        foreach ($user_send as $key => $value) {
                        $self_jgz = $value['amountSum'] / 100;
                        $arr[$key]['store_id'] = $store_id;
                        $arr[$key]['id'] = $value['id'];
                        $arr[$key]['grade'] = '会员';
                        $arr[$key]['jgz'] = $self_jgz;
                        $arr[$key]['reward'] = 0;
                if(in_array($value['id'],$userIds)){
                        $arr[$key]['grade'] = $gradeInfo[$value['grade']]['label'];
                        // 遍历得出 用户应得奖金 发放金额小于0.01元则
                        $self_reward = floor($person_get * $self_jgz);
                        if ($self_reward < 1) {
                            continue;
                        }
                        $arr[$key]['reward'] = $self_reward;
                        $send_reward += $self_reward;
                }
            
        }

        //当前帐号所属店铺 或者超管选择店铺 团队奖励名称
        if($store_id == 0){
            $awardName = '订单指数';
        }else{
            $teamAward = new TeamAward;
            $team = $teamAward->awardGold($store_id);
            $awardName = $team->award_name;
        }
        if(!empty($request->report)){
            return Excel::download(new OnePoolExport($arr), 'one_pool.xlsx');
        }

        $data = [];
        $data['data'] = $arr;// 每人数据
        $data['total'] = count($arr);// 总人数
        $data['reward'] = $poolSum;// 总奖金
        $data['jgz'] = $amountSum;// 总军功章
        $data['person_get'] = $person_get;// 军功章单价
        $data['send_reward'] = $send_reward;// 放出的奖金, 与应发放奖金有一定的差值
        $data['awardName'] = $awardName;// 团队奖励名称
        $data['path'] = env('APP_URL').'/member/jgz_list';
        return $this->success($data);
    }

    public function jgz_send(Request $request)
    {
        $User = new User;
        $Order = new Order;
        $DealRecord = new DealRecord;
        $pool = new TotalBonusPool;
        
        // 读取店铺ID
        $user = Auth::guard('admin')->user();
        if ($user->store_id === 0) {
            // 超管必需选择店铺
            $store_id = $request['storeId'];
            if (empty($store_id)) {
                return self::errorClient(['info' => '请输入店铺ID']);
            }
        } else {
            // 否则 获取用户本身代表的店铺
            $store_id = $user->store_id;
        }

        $beg = date('Y-m-1 00:00:00',strtotime('last month'));
        $end = date('Y-m-d 23:59:59',strtotime(date('Y-m-1').'-1 day'));
        
        $min_level_arr = TeamAward::where('store_id', $store_id)->first();

        //上个月总军功章  需要结算的总军功章
        $user_send = $DealRecord->join('users as u','u.id',"=",'deal_records.user_id')
         ->where('deal_records.store_id',$store_id)->where('deal_records.jm_type',3)->where('deal_records.status',3)->where('deal_records.is_set',0)->whereBetween('deal_records.created_at',[$beg, $end])
         ->groupBy('deal_records.user_id')
         ->select('u.id',DB::raw('SUM(deal_records.amount) as amountSum'),'u.gold','u.grade','u.jgz','u.grade_at','u.is_partner','u.partner_at')
         ->get()->toArray();
        
        $userIds = [];
        foreach ($user_send as $key => $value) {
            //VIP
                if($value['grade'] >= $min_level_arr['min_level'] && $value['grade_at'] <= $end){
                    //需要发放奖金的用户
                    array_push($userIds,$value['id']);
                }
                //报单中心
                if($value['is_partner'] == 1 && $value['partner_at'] <= $end){
                    //需要发放奖金的用户
                    array_push($userIds,$value['id']);
                }
        }
        $userIds = array_unique($userIds);
        $amountSum = $DealRecord->whereIn('user_id',$userIds)->where('store_id',$store_id)->where('jm_type',3)->where('status',3)->where('is_set',0)->whereBetween('created_at',[$beg, $end])->sum('amount');
        $amountSum = $amountSum/100;
        if ($amountSum == 0) {
            return self::errorClient(['info' => $min_level_arr['award_name'].'为0，无可发放内容']);
        }
        
        //上个月总奖金  1号奖金池总计
        $poolModel = $DealRecord->where('store_id',$store_id)->whereIn('deal_type',[21,30])->where('status',3)->where('is_set',0)->whereBetween('created_at',[$beg, $end]);
        $poolSum = $poolModel->sum('amount');
        $poolSum = $poolSum/100;

        //上个月所有订单指数及1号奖金池记录ID 更新结算状态
        $dealModel = $DealRecord->where('store_id',$store_id)->where('jm_type',3)->where('status',3)->where('is_set',0)->whereBetween('created_at',[$beg, $end]);
        $flist = $dealModel->select('id')->get()->toArray();
        $fIds = array_column($flist,'id');

        $plist = $poolModel->select('id')->get()->toArray();
        $pIds = array_column($plist,'id');
        $dealIds = array_unique(array_merge($fIds,$pIds));

        //保留两位小数  不四舍五入  小数位取小数点后两位
        $num = ($poolSum/$amountSum)*1000;
        if($num >= 1){
            $person_get = floor($num)/1000;
        }else{
            $person_get = 0;
        }
        $send_reward = 0;// 发放出的奖金, 与应发放奖金有一定的差值, 得到差值 并 进行处理
        $arr = [];
        $jgz_record = [];// 军功章折换余额记录
        $jgz_re = [];// 军功章扣除记录
        DB::beginTransaction();
        try {
            foreach ($user_send as $key => $value) {

                // 军功章扣除记录生成
                $jgz_re['type'] = 'out';
                $jgz_re['store_id'] = $store_id;
                $jgz_re['user_id'] = $value['id'];
                $jgz_re['status'] = 1;
                $jgz_re['reason'] = $min_level_arr['award_name'].'扣除';
                $jgz_re['deal_type'] = 20;// 军功章折算余额
                $jgz_re['deal_item_id'] = 0;
                $jgz_re['order_type'] = 5;
                $jgz_re['jm_type'] = 3;
                $jgz_re['grade'] = $value['grade'];
                $jgz_re['mark'] = '';
                $jgz_re['amount'] = $value['amountSum'];
                $jgz_re['created_at'] = date('Y-m-d H:i:s');
                $jgz_re['last_balance'] = $value['jgz'];
                $new_balance = $value['jgz'] - $value['amountSum'];
                $jgz_re['new_balance'] = $new_balance;
                $goldresult = $DealRecord->deductMoney($jgz_re);
                if ($goldresult['code'] != 20000) {
                    return $goldresult;
                }

                if(in_array($value['id'],$userIds)){
                    // 遍历得出 用户应得奖金 发放金额小于0.01元则
                    $self_jgz = $value['amountSum'] / 100;
                    $self_reward = floor($person_get * $self_jgz);
                    if ($self_reward < 1) {
                        continue;
                    }
                    $arr[$value['id']]['id'] = $value['id'];
                    $arr[$value['id']]['jgz'] = $value['amountSum'] / 100;
                    $arr[$value['id']]['reward'] = $self_reward;
                    $send_reward += $self_reward;
                    // 奖金发放
                    $jgz_record['store_id'] = $store_id;
                    $jgz_record['user_id'] = $value['id'];
                    $jgz_record['status'] = 3;
                    $jgz_record['reason'] = $min_level_arr['award_name'].'发放';
                    $jgz_record['deal_item_id'] = 0;
                    $jgz_record['order_type'] = 5;
                    $jgz_record['grade'] = $value['grade'];
                    $jgz_record['mark'] = '';

                    $jgz_record['deal_type'] = 10;// 军功章折算余额
                    $jgz_record['jm_type'] = 1;
                    $jgz_record['amount'] = $self_reward*100;
                    $jgz_record['last_balance'] = $value['gold'];
                    $goldreturned = $DealRecord->returnedMoney($jgz_record);
                    if ($goldreturned['code'] != 20000) {
                        return $goldreturned;
                    }
                }
            }
            //1号奖金池金额更新 交易记录及1号奖金池总金额更新
            $dealGold = [];
            $dealGold['store_id'] = $store_id;
            $dealGold['status'] = 1;
            $dealGold['deal_item_id'] = '';
            $dealGold['order_type'] = 5;// 会员订单
            $dealGold['jm_type'] = 1;// 余额
            $dealGold['user_id'] = 1;//奖金池收入 不更新用户表余额
            $dealGold['grade'] = 0;
            $dealGold['mark'] = date('Ymd').'订单指数结算,虹包发放当月累计金额(发放剩余累计在虹包)';
            $dealGold['amount'] = $send_reward*100;
            $dealGold['reason'] = '虹包扣除';
            $dealGold['deal_type'] = 26;// 1号奖金池金额扣除
            $poolresult = $DealRecord->deductMoney($dealGold, 1);
            if ($poolresult['code'] != 20000) {
                return $poolresult;
            }
            //已结算的订单指数交易记录状态已更新
            $dealresult = $DealRecord->whereIn('id',$dealIds)->update(['is_set'=>1]);
            if ($poolresult && $dealresult) {
                DB::commit();
                return self::successClient(['info' => '结算成功']);
            } else {
                return self::errorClient(['info' => '结算失败']);
            }
        } catch (\Exception $e) {
            DB::rollBack();
            return $e;
            return $e->getLine().$e->getMessage();
        }
    }
    public function getList(Request $request)
    {
        $pageSize = $request['pageSize'];
        $storeId = $request['storeId'];
        $userId = $request['userId'];
        $phone = $request['phone'];
        $grade = $request['grade'];
        $report = $request['report'];

        $userModel = new User;
        $data = $userModel->getList($pageSize, $storeId, $phone, $userId, $grade, $report);

        return $data;
    }

    public function handle(Request $request)
    {
        $id = $request['id'];
        $data = $request['data'];
        $type = $request['type'];
        $handleType = $request['handleType'];
        $mark = $request['mark'];

        $userModel = new User;
        $data = $userModel->handle($id, $data, $type, $handleType, $mark);

        return $data;
    }

    public function getTree(Request $request)
    {
        $storeId = $request['storeId'];
        $userId = $request['userId'];
        if (empty($userId)) {
            $userId = 1;
        }

        $userModel = new User;
        $data = $userModel->getTree($storeId, $userId);

        return $data;
    }

    //月度报单中心结算列表
    public function teamMonthList(Request $request){
         // 读取店铺ID
         $user = Auth::guard('admin')->user();
         if ($user->store_id === 0) {
             // 超管必需选择店铺
             $store_id = $request['storeId'];
             if (empty($store_id)) {
                 return self::errorClient(['info' => '请输入店铺ID'.$store_id]);
             }
         } else {
             // 否则 获取用户本身代表的店铺
             $store_id = $user->store_id;
         }
         $deal = new DealRecord;
         $beg = date('Y-m-1 00:00:00',strtotime('last month'));
         $end = date('Y-m-d 23:59:59',strtotime(date('Y-m-1').'-1 day'));

         //获取上月月度报单中心总奖金
         $teamMonthSum = $deal->getAmountSum($store_id,22,$beg,$end)/100;
         //获取上月推荐报单中心总奖金
         $teamRecommend = $deal->getAmountSum($store_id,24,$beg,$end)/100;
         
         if($teamMonthSum == 0 && $teamRecommend == 0){
            return self::errorClient(['info' => '没有金额需要发放']);
         }  

         //获取每个用户生成的月度报单中心总奖金
         $userMonth = $deal->userAmountSum($store_id,22,$beg,$end);

         //获取每个用户生成的推荐报单中心总奖金
         $userRecommend = $deal->userAmountSum($store_id,24,$beg,$end);

         //报单中心应获取的月度报单中心奖金和推荐报单中心奖金
         $arr = $deal->teamData($userMonth,$userRecommend);
         foreach ($arr as $key => $value) {
             $arr[$key]['month'] = $value['month']/100; 
             $arr[$key]['recommend'] = $value['recommend']/100; 
         }

         if(!empty($request->report)){
            return $deal->handleImportTeamMonthData($store_id,$beg,$end);
         }

         $data = [];
         $data['monthSum'] = $teamMonthSum;
         $data['recommendSum'] = $teamRecommend;
         $data['path'] = env('APP_URL').'/member/team_month_list';
         $data['data'] = array_values($arr);
         return $this->success($data); 
    }

    //月度报单中心结算发放
    public function teamMonthSend(Request $request){
        // 读取店铺ID
        $user = Auth::guard('admin')->user();
        if ($user->store_id === 0) {
            // 超管必需选择店铺
            $store_id = $request['storeId'];
            if (empty($store_id)) {
                return self::errorClient(['info' => '请输入店铺ID'.$store_id]);
            }
        } else {
            // 否则 获取用户本身代表的店铺
            $store_id = $user->store_id;
        }
        
        $deal = new DealRecord;
        $result= $deal->teamMonthSend($store_id);
        return $result;
    }

    //店铺总金额
    public function goldSum(Request $request){
        // 读取店铺ID
        $user = Auth::guard('admin')->user();
        if ($user->store_id === 0) {
            // 超管必需选择店铺
            $store_id = $request['storeId'];
            if (empty($store_id)) {
                return self::errorClient(['info' => '请输入店铺ID'.$store_id]);
            }
        } else {
            // 否则 获取用户本身代表的店铺
            $store_id = $user->store_id;
        }

        if(!empty($request->report)){
            $deal = new DealRecord;
            return $deal->handleImportBonusData($store_id,$request->type);
        }

        $pool = new TotalBonusPool;
        $bonus = $pool->where('store_id',$store_id)->first();
        //公司账号余额
        $user = new User;
        $company = $user->where('id',1)->first();
        
        $data = [];
        $info = [];
        $arr = [];
        $arr['store_id'] = $store_id;
        $arr['gold_sum'] = $company->gold/100;
        $arr['bonus_pool_one_sum'] = $bonus->bonus_pool_one_sum/100;
        $arr['team_month_sum'] = $bonus->team_month_sum/100;
        $arr['team_year_sum'] = $bonus->team_year_sum/100;
        $arr['team_recommend_sum'] = $bonus->team_recommend_sum/100;
        $arr['team_fund_sum'] = $bonus->team_fund_sum/100;
        $arr['total'] =  $arr['gold_sum'] + $arr['bonus_pool_one_sum'] + $arr['team_month_sum'] + $arr['team_year_sum'] + $arr['team_recommend_sum'] + $arr['team_fund_sum'];
        array_push($info,$arr);
        $data['data'] = $info;
        $data['path'] = env('APP_URL').'/member/gold_sum';
        return $this->success($data);
    }

    //扣除公司账号余额
    public function deduct(Request $request){
        $data = $request->data;
        $reason = $request->reason;
        $DealRecord = new DealRecord;
        $dealGold = [];
        $dealGold['store_id'] = 3;
        $dealGold['status'] = 1;
        $dealGold['deal_item_id'] = 0;
        $dealGold['order_type'] = 4;// 会员订单
        $dealGold['jm_type'] = 1;
        $dealGold['user_id'] = 1;
        $dealGold['grade'] = 0;
        $dealGold['mark'] = $reason;
        $dealGold['amount'] = $data*100;
        $dealGold['reason'] = '公司余额扣除';
        $dealGold['deal_type'] = 34;
        $goldReturned = $DealRecord->deductMoney($dealGold);
        if ($goldReturned['code'] != 20000) {
            return $goldReturned;
        }
        return $this->success("操作成功");
    }



    //每日金额
    public function dailyAmount(Request $request){
        // 读取店铺ID
        $user = Auth::guard('admin')->user();
        if ($user->store_id === 0) {
            // 超管必需选择店铺
            $store_id = $request['storeId'];
            if (empty($store_id)) {
                return self::errorClient(['info' => '请输入店铺ID'.$store_id]);
            }
        } else {
            // 否则 获取用户本身代表的店铺
            $store_id = $user->store_id;
        }

        $amount = new DailyAmount;
        $list = $amount->where('store_id',$store_id)->orderBy('created_time','desc')->get()->toArray();
        $data = [];
        foreach ($list as $key => $value) {
            $list[$key]['gold'] = $value['gold']/100;
            $list[$key]['member_gold'] = $value['member_gold']/100;
            $list[$key]['bonus_pool_one'] = $value['bonus_pool_one']/100;
            $list[$key]['team_month'] = $value['team_month']/100;
            $list[$key]['team_year'] = $value['team_year']/100;
            $list[$key]['team_recommend'] = $value['team_recommend']/100;
            $list[$key]['team_fund'] = $value['team_fund']/100;
        }
        if(!empty($request['report'])) {
            return Excel::download(new DailyAmountExport($list), 'DailyAmount.xlsx');
        }
        $data['data'] = $list;
        $data['path'] = env('APP_URL').'/member/daily_amount';
        return $this->success($data);
    }

    public function transferList(Request $request){
        // 读取店铺ID
        $user = Auth::guard('admin')->user();
        if ($user->store_id === 0) {
            // 超管必需选择店铺
            $store_id = $request['storeId'];
            if (empty($store_id)) {
                return self::errorClient(['info' => '请输入店铺ID'.$store_id]);
            }
        } else {
            // 否则 获取用户本身代表的店铺
            $store_id = $user->store_id;
        }
        $deal = new DealRecord;
        $amount = $deal->surplusAmount($store_id,$request->type);
        return $this->success($amount);
    }

    public function transfer(Request $request){
        $store_id = $request->storeId;
        $deal = new DealRecord;
        return $deal->transfer($store_id,$request->type,$request->user_id,$request->reason,$request->amount);
    }


    //分虹列表
    public function flhList(Request $request){
        // 读取店铺ID
        $user = Auth::guard('admin')->user();
        if ($user->store_id === 0) {
            // 超管必需选择店铺
            $store_id = $request['storeId'];
            if (empty($store_id)) {
                return self::errorClient(['info' => '请输入店铺ID'.$store_id]);
            }
        } else {
            // 否则 获取用户本身代表的店铺
            $store_id = $user->store_id;
        }

        $deal_record = new DealRecord;
        $data = $deal_record->flhList($store_id,$request->report);
        return $data;
    }

    //分虹发放
    public function flhSend(Request $request){
        // 读取店铺ID
        $user = Auth::guard('admin')->user();
        if ($user->store_id === 0) {
            // 超管必需选择店铺
            $store_id = $request['storeId'];
            if (empty($store_id)) {
                return self::errorClient(['info' => '请输入店铺ID'.$store_id]);
            }
        } else {
            // 否则 获取用户本身代表的店铺
            $store_id = $user->store_id;
        }
        
        $deal = new DealRecord;
        $result= $deal->flhSend($store_id);
        return $result;
    }
}
